package com.jeeplus.modules.monitor.task;

import org.apache.shiro.util.ThreadContext;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.modules.grouporder.entity.GroupOrder;
import com.jeeplus.modules.grouporder.service.GroupOrderService;
import com.jeeplus.modules.monitor.entity.Task;

/**
 * 取消拼团未付款订单
 * @author Administrator
 *
 */
@DisallowConcurrentExecution  
public class CancelGroupOrderTask extends Task {
	private static GroupOrderService groupOrderService = SpringContextHolder.getBean(GroupOrderService.class);

	private static final org.apache.shiro.mgt.SecurityManager MANAGER = SpringContextHolder.getBean(org.apache.shiro.mgt.SecurityManager.class);
	private static Logger logger = LoggerFactory.getLogger(CancelGroupOrderTask.class);
	
	@Override
	public void run() {
		if (ThreadContext.getSecurityManager() == null) {
			ThreadContext.bind(MANAGER);
		}
		// 拼团订单
		GroupOrder groupOrder = new GroupOrder();
		groupOrder.setState("0");
		groupOrder.setDataScope(" AND a.create_date < DATE_SUB(NOW(),INTERVAL 24 HOUR) ");
		int pageNo = 1;
		while (true) {
			Page<GroupOrder> page = groupOrderService.findPage(new Page<GroupOrder>(pageNo, 100), groupOrder);
			if (!page.getList().isEmpty()) {
				for (GroupOrder order : page.getList()) {
					order.setState("5");
					order.setCancelReason("超时未付款");
					order.setCancelDate(DateUtils.addHours(order.getCreateDate(), 24));
					try {
						groupOrderService.cancel(order);
					} catch (Exception e) {
						logger.error("拼团订单" + order.getId() + "取消失败：" + e.getMessage());
					}
				}
			}
			if (page.getList().size() < 100) {
				break;
			}
			pageNo++;
		}
	}
}
